-- UIGenieLamp
-- Created by zouyb Sep/25/2015
-- 神灯

-- 选项数量
local MAX_OPTION_NUM = 3;

UIGenieLamp = class("UIGenieLamp", function()
    return cc.Layer:create();
end);

function UIGenieLamp.create(altarId, gridData, itemId)
    return UIGenieLamp.new(altarId, gridData, itemId);
end

-- 按钮数量
local BTN_COUNT = 4;

-- 构造函数
function UIGenieLamp:ctor(altarId, gridData, itemId)
    self:setName("UIGenieLamp");

    -- 重用神龙许愿的界面
    local node = cc.CSLoader:createNode("layout/dragon/DragonWish.csb");
    self:addChild(node);
    self.node = node;

    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    self.gridData  = gridData;
    self.altarId = altarId;
    self.itemId = itemId;

    -- 初始化窗口
    self:initForm();

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 适配
function UIGenieLamp:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- 特效节点居中缩放至合适大小
    AlignM.alignToCenter(node, "effect_node");
end

-- 注册事件处理回调函数
function UIGenieLamp:registerEventCallback()
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            cclog("UIGenieLamp 界面析构清理");
        elseif eventType == "enter" then
        end
    end);
end

-- 获取神灯动画
local function getGenieAnim(pos)
    local uiDungeon = UIDungeonMgr.getCurLevel();
    local uiGrid = uiDungeon:getAllGrids()[pos];
    return uiGrid.effectAnim;
end

-- 神灯愿望实现后的动画1
local function playGenieWishDoneEffect1(optionId, pos, callback)
    -- 获取神灯动画
    local effectAnim = getGenieAnim(pos);
    if effectAnim == nil then
        callback();
        return;
    end

    -- 获取选项类型
    local classify = DesertAltarM.query(optionId, "classify");

    if classify == "summon" then
        -- 类型为协助战斗, 播放战斗准备动作, 然后再进行后续动作
        effectAnim:play(241, 296, false, 0.5, callback);
        AudioM.playFx("aladin2");
    else
        -- 其他， 播放许愿效果，进行奖励
        effectAnim:play(200, 236, false, 0.5, callback);
        AudioM.playFx("aladin1");
    end
end

-- 神灯愿望实现后的动画2
local function playGenieWishDoneEffect2(optionId, pos)
    -- 获取神灯动画
    local effectAnim = getGenieAnim(pos);
    if effectAnim == nil then
        return;
    end

    -- 效果提示
    local desc = DesertAltarM.query(optionId, "desc");

    -- 获取选项类型
    local classify = DesertAltarM.query(optionId, "classify");
    print("desert altar classfy:" .. classify);

    if classify == "summon" then
        local parent = effectAnim:getParent();
        local posX = effectAnim:getPositionX();
        local posY = effectAnim:getPositionY();
        playEffect(parent, 1254, posX + 20, posY + 80);

        -- 类型为协助战斗, 已经召唤出怪物了，删除动画本身
        -- effectAnim:removeFromParent();
        effectAnim:setVisible(false);

        -- 效果提示
        performWithDelay(UIMgr.getCurrentScene(), function() alert(desc); end, 0.8);
    else
        local uiDungeon = UIDungeonMgr.getCurLevel();
        local uiGrid = uiDungeon:getAllGrids()[pos];

        if classify ~= "upgrade" and classify ~= "special" then
            -- 有奖励物品或属性的，播放额外效果
            local function callback()
                -- 播放光圈效果
                playEffect(uiGrid, 1134, 0, 20);

                -- 效果提示
                alert(desc);
            end
            performWithDelay(uiGrid, callback, 0.7);
        else
            -- 效果提示
            performWithDelay(UIMgr.getCurrentScene(), function() alert(desc); end, 0.8);

            uiDungeon:updateUI();
        end

        -- 其他， 播放消失效果
        local function hide()
            print("隐藏神灯")
            effectAnim:setVisible(false);
        end
        effectAnim:play(72, 104, false, 0.5, hide);
    end
end

-- 注册点击事件
function UIGenieLamp:redraw()
    -- 查询建筑配置
    local class = self.gridData.class;
    local title = BuildingBonusM.queryBuildingView(class);

    local CT = findChildByName(self.node, "CT");

    -- 显示tip
    local tip1Label = findChildByName(CT, "tip1");
    tip1Label:setPositionY(tip1Label:getPositionY() - 17);
    TextStyleM.setTextStyle(tip1Label, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    tip1Label:setString(self:getDialog());

    local tip2Label = findChildByName(CT, "tip2");
    tip2Label:setVisible(false);

    local options = self.gridData.options[self.altarId];
    printTable(options, "UIGenieLamp, options");

    -- 显示选项
    local kerning = 0;
    if getLang() ~= "zh" and getLang() ~= "tw" then
        kerning = -1;
    end
    for i = 1, MAX_OPTION_NUM do
        local btn = findChildByName(CT, "button" .. i);
        if i > #options then
            btn:setVisible(false);
        else
            btn:setVisible(true);

            TextStyleM.setTextStyle(btn, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, kerning);
            btn:setTitleText(DesertAltarM.query(options[i], "text"));
            btn:setTag(i);

            -- 注册选项点击事件
            local function onClick(sender, eventType)
                if eventType == ccui.TouchEventType.ended then
                    if not self:isVisible() then
                        return;
                    end

                    AudioM.playFx("button_select");

                    local function callback()
                        -- 选择某选项
                        local data = bit.blshift(self.altarId, 16) + options[i];
                        DungeonActionM.go("desert_altar", self.gridData:getPos(), data);

                        -- 提示愿望已满足
                        alert(getLocStr("your_wish_is_achieved"));

                        -- 神灯愿望实现后的动画2
                        playGenieWishDoneEffect2(options[i], self.gridData:getPos());

                        closeFormByName("UIInvisibleForm");

                        UIMgr.getCurrentScene():removeFormByName("UIGenieLamp");
                        UIMgr.getCurrentScene():removeFormByName("UIDesertAltar");

                        -- 抛出事件，有些东西需要重绘（比如怪物攻击）
                        EventMgr.fire(event.PLAYER_MOVE, {["combatRound"] = true});
                    end

                    -- 神灯愿望实现后的动画1
                    playGenieWishDoneEffect1(options[i], self.gridData:getPos(), callback);

                    -- 先隐藏窗口
                    self:setVisible(false);

                    wait();
                end
            end
            btn:addTouchEventListener(onClick);
        end
    end
end

-- 获取讲话内容
function UIGenieLamp:getDialog()
    if self.altarId == 1 then
        return getLocStr("genie_1_dialog");
    elseif self.altarId == 2 then
        return getLocStr("genie_2_dialog");
    elseif self.altarId == 3 then
        return getLocStr("genie_3_dialog");
    end

    return "unkonwn";
end

-- 初始化窗口
function UIGenieLamp:initForm()
    -- 先将主窗口隐藏
    local CT = findChildByName(self.node, "CT");
    self.CT = CT;
    CT:setVisible(false);

    -- 播放神灯出现特效
    self:playGenieAppear();
end

-- 播放神灯出现特效
function UIGenieLamp:playGenieAppear()
    local effectNode = findChildByName(self.node, "effect_node");
    playEffect(effectNode, 1255, -3, -15);

    local function callback()
        -- 窗口从中心位置出现
        local initScale = self.CT:getScale();
        self.CT:setVisible(true);
        self.CT:setScale(0.15*initScale);

        -- 先放大再缩小
        self.CT:stopAllActions();
        local referTime = 0.15;
        local upTime    = 1.5*referTime;
        local downTime  = 2*referTime;
        local scaleUp   = cc.ScaleTo:create(upTime, 1.1*initScale);
        local scaleDown = cc.ScaleTo:create(downTime, 0.95*initScale);

        self.CT:runAction(cc.Sequence:create(cc.Spawn:create(scaleUp), scaleDown));
    end

    performWithDelay(self, callback, 2.1);
end







